import qiniu from 'qiniu'
import axios from 'axios';
import dayjs from "dayjs";
// 读取env文件
import dotenv from 'dotenv';
// 配置Access Key 和 Secret Key
dotenv.config();
const accessKey = process.env.QINIU_ACCESS_KEY;
const secretKey = process.env.QINIU_SECRET_KEY;
console.log(accessKey, secretKey)
// 创建Auth对象实例
const auth = new qiniu.auth.digest.Mac(accessKey, secretKey);
const putPolicy = new qiniu.rs.PutPolicy({ scope: process.env.QINIU_BUCKET });

// 生成上传凭证
function uptoken() {
    return putPolicy.uploadToken(auth);
}
const config = new qiniu.conf.Config();
const localFile = "/Users/enchanter/icar-api/public/test.png";
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();
const key='lasting/' + dayjs().format('YYYYMMDDHHmmss') + 'test.png';
export const uploadImage = ({ filePath = localFile }) => {
    return new Promise((resolve, reject) => {
        formUploader.putFile(uptoken(), key, filePath, putExtra)
            .then(({ data, resp }) => {
                if (resp.statusCode === 200) {
                    resolve(data);
                }
            })
    })
}
export const uploadImageByStream = (stream) => {
    return new Promise((resolve, reject) => {
        formUploader.putStream(uptoken(), key, stream, putExtra)
            .then(({ data, resp }) => {
                if (resp.statusCode === 200) {
                    resolve(data);
                }
            })
    })
}

export const transferStore = async (url) => {
    const response = await axios({
        url,
        method: 'GET',
        responseType: 'stream'
    });
    return uploadImageByStream({ ...response.data, url: 'https://cdn.enchanter.tech/' + response.data.key });
}
export default {
    uploadImage,
    uploadImageByStream,
    transferStore
}

